package com.plateno.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.plateno.bean.model.SensitiveWord;
import com.plateno.cache.InstanceHolder;
import com.plateno.mapper.SensitveWordMapper;
import com.plateno.util.JsonUtil;

@Service
public class SensitiveWordInitService {
	
	protected final Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	public SensitveWordMapper sensitveWordMapper;
	
	/**
	 * 构建敏感词
	 * 
	 *可以去掉set的转换，少一个循环直接使用list循环添加到map中
	 * 
	 * @param sensitiveWords
	 * @return
	 */
	public void loadKeyWord() {
		try {
			log.info("敏感词初始化开始");
			long start = System.currentTimeMillis();
			//从数据库加载敏感词
			List<SensitiveWord> sensitiveWords = sensitveWordMapper.getAll();
			// 将敏感词库加入到HashMap中
			addSensitiveWordToHashMap(sensitiveWords);
			log.info("敏感词初始化开始耗时：" + (System.currentTimeMillis() - start) + " ms");
		} catch (Exception e) {
			log.error("敏感词初始化开始任务失败", e);
		}
	}

	/**
	 * 封装敏感词库
	 * 
	 * @param keyWordSet
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void addSensitiveWordToHashMap(List<SensitiveWord> sensitiveWords) {
		Map sensitiveWordMap = InstanceHolder.sensitiveWordLocalCache(); // 初始化敏感词容器，减少扩容操作
		List sensitiveWordList = InstanceHolder.sensitiveWordListLocalCache();
		sensitiveWordMap.clear();
		String key = null;
		Map nowMap = null;
		Map<String, String> newWorMap = null;
		// 迭代keyWordSet
//		Iterator<String> iterator = keyWordSet.iterator();
		//直接使用返回作为循环对象
		for (SensitiveWord s : sensitiveWords) {
			key = s.getSensitiveWord().trim(); // 关键字
			if (StringUtils.isEmpty(key)) {
				continue;
			}
			sensitiveWordList.add(key);
			nowMap = sensitiveWordMap;
			for (int i = 0; i < key.length(); i++) {
				char keyChar = key.charAt(i); // 转换成char型
				Object wordMap = nowMap.get(keyChar); // 获取

				if (wordMap != null) { // 如果存在该key，直接赋值
					nowMap = (Map) wordMap;
				} else { // 不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
					newWorMap = new HashMap<String, String>();
					newWorMap.put("isEnd", "0"); // 不是最后一个
					nowMap.put(keyChar, newWorMap);
					nowMap = newWorMap;
				}

				if (i == key.length() - 1) {
					nowMap.put("isEnd", "1"); // 最后一个
				}
			}
		}
		try {
			log.info("DFA树:"+JsonUtil.toJsonString(sensitiveWordMap));
		} catch (IOException e) {
		}
	}
	
	
	
	
	
	
}
